package javadiff;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;



public class JavaDiff {
	static ArrayList<String> firstText=new ArrayList<String>();
	static ArrayList<String> secondText=new ArrayList<String>();
	static ArrayList<String> outputText=new ArrayList<String>();
	static String firstActual;
	static String secondActual;
	
	static Scanner firstReader;
	static Scanner secondReader;
	static BufferedWriter writer;
	static BufferedWriter logWriter;
	
	public static void main(String[] args){
		
		try {
			firstReader=new Scanner(new FileReader(args[0]));
			secondReader=new Scanner(new FileReader(args[1]));
			writer=new BufferedWriter(new FileWriter(args[0]+".diff"));
			logWriter=new BufferedWriter(new FileWriter("JavaDiffLog",true));
		}catch (IndexOutOfBoundsException e) {
			System.out.print("not enough arguments!");
			System.exit(0);
		}catch (FileNotFoundException e) {
			System.out.print("file(s) not found)");
			System.exit(0);
		} catch (IOException e) {
			System.out.print("write error!");
		}
		

		while(firstReader.hasNextLine()){
			String line=firstReader.nextLine();
			if(!line.equals(""))
			firstText.add(line);
		}
		
		while(secondReader.hasNextLine()){
			String line=secondReader.nextLine();
			if(!line.equals(""))
			secondText.add(line);
		}
		
		
		
		ArrayList<String> firstCopy=new ArrayList<String>(firstText);
		ArrayList<String> secondCopy=new ArrayList<String>(secondText);
		
		Iterator<String> firstIt=firstCopy.iterator();
		Iterator<String> secondIt;
		
		while(firstIt.hasNext()){
			firstActual = firstIt.next();
			secondIt=secondCopy.iterator();
			while(secondIt.hasNext())
				if(firstActual.equals(secondIt.next())){
					secondIt.remove();
					firstIt.remove();
				}
		}
		
		firstIt=firstCopy.iterator();
		secondIt=secondCopy.iterator();
		
		try {
			if(firstIt.hasNext()&&secondIt.hasNext()){
				logWriter.write(args[0]+", " + args[1] + ": match");
				logWriter.newLine();}
			else{
				logWriter.write(args[0]+", "+ args[1] + ": differ");
				logWriter.newLine();
			}
			
			
			writer.write("<<<");
			writer.newLine();
			while(firstIt.hasNext()){
				writer.write(firstIt.next());
				writer.newLine();
			}
			writer.write("===");
			writer.newLine();
			while(secondIt.hasNext()){
				writer.write(secondIt.next());
				writer.newLine();
			}
			writer.write(">>>");
			writer.newLine();
		} catch (IOException e) {
			System.out.print("write error!");
		}
		
		
		
		firstReader.close();
		secondReader.close();
		try {
			writer.close();
			logWriter.close();
		} catch (IOException e) {
			System.out.print("write error!");
		}
	}
}
